/**
 * @description vite自定义插件 - 前端版本校验
 * @lastModify 2024-12-13
 * @author 叶花弈
 */

export default (options = { intervalTime: 3 * 1000 }) => {
  const { intervalTime } = options;
  const script = `
    let lastCheckTime = null;
    // 校验浏览器html文件
    const checkWebVersion = async () => {
      if (lastCheckTime === null || new Date().getTime() - lastCheckTime > ${intervalTime}) {
        try {
          const url = window.location.origin + window.location.pathname;
          const res = await fetch(url + '?v=' + new Date().getTime());
          const HTMLString = await res.text();
          if (window._HTMLString !== HTMLString) {
            ElMessage({
              showClose: true,
              message: "系统已有更新, 请刷新页面!",
              type: "warning",
              duration: 0,
            });
          }
          lastCheckTime = new Date().getTime();
        } catch (error) {
          throw new Error(error);
        }
      }
    };
    // 存储当前浏览器html文件 + 绑定校验触发事件
    fetch(window.location.origin + window.location.pathname).then(async res => {
      window._HTMLString = await res.text();
      // 点击事件绑定校验
      window.addEventListener("click", () => {
        checkWebVersion();
      });
      // XHR请求绑定校验
      const oldOpen = XMLHttpRequest.prototype.open;
      XMLHttpRequest.prototype.open = function (method, url) {
        checkWebVersion();
        oldOpen.apply(this, arguments);
      };
    })
  `;
  return {
    name: "vite-plugin-webVersion",
    transform(code, id) {
      if (id.endsWith("main.js")) return `${code}\n${script}`;
    },
  };
};
